<?php

namespace App\Http\Controllers\Laifei\Work;

use App\Http\Controllers\Controller;
use App\Models\Common\Common;
use App\Models\Tools\Data;
use App\Models\Tools\Period;
use App\Models\Work;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LaifeiWorkAcceptController extends Controller
{
    /**
     * 验收
     */

    public function index()
    {

        $all = $this->all;

        $work_id = $all['work_id'];
        $accept_remark = $all['accept_remark'];
        $accept = $all['accept'];

        try {
            DB::beginTransaction();
            // 检查当前工单状态，仅为已投稿状态可以验收(写锁)
            $work_msg = DB::table('explore_work')
                ->where('work_id', '=', $work_id)
                ->lockForUpdate()
                ->first();
            $work_msg = json_decode(json_encode($work_msg), true);
            if ($work_msg['status'] !== Data::DATA_DB_EXPLORE_WORK_STATUS_SUBMIT) {
                DB::rollBack();
                return $this->setReturnJson(-1, '当前工单状态不允许验收，请刷新重试');
            }

            // 验收通过
            if ($accept) {
                $success_msg = '验收成功';
                // 修改状态
                DB::table('explore_work')
                    ->where('work_id', '=', $work_id)
                    ->update([
                        'status' => Data::DATA_DB_EXPLORE_WORK_STATUS_ACCEPTED,
                        'accept_time' => date('Y-m-d H:i:s'),
                        'accept_user' => $this->userInfo['id'],
                        'accept_remark' => $accept_remark,
                    ]);
                // 记录日志
                DB::table('explore_work_log')->insert([
                    'work_id' => $work_id,
                    'action' => Data::DATA_DB_EXPLORE_WORK_ACTION_ACCEPTED,
                    'user_id' => $this->userInfo['id'],
                    'remark' => '管理员【' . $this->userInfo['name'] . '】验收投稿，验收备注：' . $accept_remark,
                ]);

                // 验收超时自动进入待结算阶段
                if(strtotime(date('Y-m-d H:i:s'))-strtotime($work_msg['submit_time']) > Period::getSetting('EXPLORE_CHECK_TIME')){
                    DB::table('explore_work')
                        ->where('work_id','=',$work_id)
                        ->update(['status' => Data::DATA_DB_EXPLORE_WORK_STATUS_CHECK]);
                    DB::table('explore_work_log')->insert([
                        'work_id' => $work_id,
                        'action' => Data::DATA_DB_EXPLORE_WORK_ACTION_CHECK,
                        'user_id' => $this->userInfo['id'],
                        'remark' => '验收投稿超时，自动进入待结算阶段',
                    ]);
                }
                // 发送验收微信通知（发送给商家）
                $data = [
                    'first' => '新的工单验收通知',
                    'keyword1' => $work_msg['work_no'],
                    'keyword2' => date('Y-m-d H:i:s'),
                    'keyword3' => '验收已通过',
                    'keyword4' => $accept_remark,
                    'keyword5' => $this->userInfo['name'],
                    'remark' => '工单已验收，详细信息请点击查看',
                ];
                //发送通知
                $openid = DB::table('lottery_users')->where('we_id','=',$work_msg['apply_we_id'])->value('openid');
                Common::sendLaifeiMessage($openid,'work_check',$data,'/history?tab=1');
            } else { // 拒回
                $success_msg = '拒回成功';
                DB::table('explore_work')
                    ->where('work_id', '=', $work_id)
                    ->update([
                        'status' => Data::DATA_DB_EXPLORE_WORK_STATUS_REFUSE,
                        'accept_user' => $this->userInfo['id'],
                        'accept_remark' => $accept_remark,
                        'refused_at' => date('Y-m-d H:i:s'),
                    ]);
                DB::table('explore_work_log')->insert([
                    'work_id' => $work_id,
                    'action' => Data::DATA_DB_EXPLORE_WORK_ACTION_REFUSE,
                    'user_id' => $this->userInfo['id'],
                    'remark' => '管理员【' . $this->userInfo['name'] . '】拒回投稿，验收备注：' . $accept_remark,
                ]);

                //  发送验收拒回微信通知（发送给达人）
                $data = [
                    'first' => '您好，您的投稿信息不符合验收要求，现已驳回。',
                    'keyword1' => '您提交的探店投稿有误，现已驳回，请重新提交',
                    'keyword2' => $this->userInfo['name'],
                    'keyword3' => $accept_remark,
                    'keyword4' => date('Y-m-d'),
                    'remark' => '点击链接重新提交投稿信息',
                ];
                //发送通知
                $openid = DB::table('lottery_users')->where('we_id','=',$work_msg['receiver_we_id'])->value('openid');
                Common::sendLaifeiMessage($openid,'work_reject',$data,'/talent/history?tab=1');
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error(LaifeiWorkAcceptController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '验收失败', ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
        }
        return $this->setReturnJson(0, $success_msg);

    }

}
